package j.framework.tags;

import j.framework.core.DictItem;
import j.framework.tags.form.FormTag;
import j.util.ForUtils;
import j.util.StringUtils;

import javax.servlet.jsp.tagext.Tag;
import java.util.List;

/**
 * User: jason
 * Date: 2014/11/7 17:14
 */
public class TagUtils {
    public static String generateDictItemsForWebSelect(final String inputName,List<DictItem> items,String changeHandler, final String selectedItem,
                                                       String theFirstItemText, String cssClass,boolean isRequired){
        final StringBuilder buff = new StringBuilder();
        buff.append("<select id=\"").append(inputName).append("\" name=\"").append(inputName).append("\"");
        if(StringUtils.isNotEmpty(changeHandler)){
            buff.append(" onchange=\"").append(changeHandler).append("(this);\"");
        }
        if(StringUtils.isNotEmpty(cssClass)){
            buff.append(" class=\"").append(cssClass).append("\"");
        }
        if(isRequired){
            buff.append(" required ");
        }
        buff.append(">");
        if(StringUtils.isNotEmpty(theFirstItemText)){
            buff.append("<option value=\"\">").append(theFirstItemText).append("</option>");
        }
        ForUtils.foreach(items, new ForUtils.ForHandler<DictItem>() {
            String code;

            @Override
            public int doFor(int index, DictItem item) {
                if (item.isDisabled()) {
                    return ForUtils.CONTINUE;
                }
                code = item.getCode();
                if (StringUtils.isNotEmpty(item.getValue())) {
                    code = item.getValue();
                }
                buff.append("<option value=\"").append(code).append("\"");
                if (null != selectedItem && selectedItem.equals(code)) {
                    buff.append(" selected=\"selected\"");
                }
                buff.append(">");
                buff.append(item.getName()).append("</option>");
                return 0;
            }
        });
        buff.append("</select>");
        return buff.toString();
    }

    public static FormTag getParentAsFormTag(Tag tag){
        Tag parentTag = tag.getParent();
        if(parentTag instanceof FormTag){
            return (FormTag)parentTag;
        }
        while(parentTag != null && ! (parentTag instanceof FormTag)){
            parentTag = parentTag.getParent();
        }
        if(parentTag!=null){
            return (FormTag)parentTag;
        }
        return null;
    }
}
